package com.example.jdbcdemo.service.Impl;

import com.alibaba.fastjson.JSON;
import com.example.jdbcdemo.mapper.GoodsMapper;
import com.example.jdbcdemo.mapper.GroupIdMapMapper;
import com.example.jdbcdemo.mapper.OrderMapper;
import com.example.jdbcdemo.mapper.ProductMapper;
import com.example.jdbcdemo.pojo.Goods;
import com.example.jdbcdemo.pojo.GroupIdMap;
import com.example.jdbcdemo.pojo.Order;
import com.example.jdbcdemo.pojo.Product;
import com.example.jdbcdemo.service.OrderServiceInterface;
import com.example.jdbcdemo.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class OrderServiceImpl implements OrderServiceInterface {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    GroupIdMapMapper groupIdMapMapper;


    /**
     * 单次进货
     * @param order
     * @return
     */
    @Override
    public JsonUtil addOrderj(Order order) {
        //2表示进货，status为默认值0（进货单不需要状态）
        groupIdMapMapper.addGroupIdMap(new GroupIdMap(order.getGroupId(),1,new Date(),0,2));
        orderMapper.addOrder(order);//添加一次进货商品
        Goods goods= goodsMapper.queryGoodsByTwo(order.getProductId(),order.getStorageId());//获得这批货物应该存到哪里
        List<Goods> goodsList = goodsMapper.queryGoodsListByProductId(order.getProductId());//获取对应的所有库存来计算商品总数
        int totalnum=order.getNumber();
        for(Goods goods1:goodsList){
            totalnum+=goods1.getNumber();
        }
        int oldnum=totalnum-order.getNumber();

        Product product = productMapper.queryProductById(order.getProductId());//获取对应的商品
        double cost = (order.getPrice() * order.getNumber() + oldnum * product.getCost()) / totalnum;
        goods.setNumber(order.getNumber() + goods.getNumber());//添加商品数量
        product.setCost(cost);//更新成本价
        goodsMapper.updateGoods(goods);
        productMapper.updateProduct(product);
        return new JsonUtil(0,"进货成功", JSON.toJSONString(order));
    }

}
